<template>
    <page-container>
        <div class="ant-pro-table">
            <div class="ant-pro-table-search">
                <a-form layout="horizontal">
                    <a-row :gutter="16" type="flex" justify="start">
                        <a-col :xs="12" :sm="12" :md="4">
                            <a-form-item hide-label>
                                <a-input-search placeholder="输入关键词名称" v-model:value="queryParams.word" allow-clear
                                    enter-button @search="handleSearch()" />
                            </a-form-item>
                        </a-col>
                        <a-col :xs="12" :sm="12" :md="3">
                            <a-form-item hide-label>
                                <a-select v-model:value="queryParams.source" @change="handleSearch()" placeholder="消息来源"
                                    :options="[
                                        {
                                            label: '单聊',
                                            value: '1',
                                        },
                                        {
                                            label: '群聊',
                                            value: '2',
                                        },
                                    ]"></a-select>
                            </a-form-item>
                        </a-col>
                        <a-col :xs="12" :sm="12" :md="4">
                            <a-form-item hide-label>
                                <a-range-picker value-format="YYYY-MM-DD" v-model:value="queryParams.time"
                                    @change="handleSearch()"></a-range-picker>
                            </a-form-item>
                        </a-col>

                        <a-col :xs="24" :sm="24" :md="12" :lg="3">
                            <!-- <a-button @click="handleSearch" type="primary">搜索</a-button> -->
                            <a-button @click="handleReset" class="ml-5px">重置</a-button>
                        </a-col>
                        <a-col :span="4">
                            <div class="ant-pro-table-list-toolbar-right">
                                <div class="ant-pro-table-list-toolbar-setting-item">
                                    <a-tooltip title="刷新">
                                        <reload-outlined @click="reload" />
                                    </a-tooltip>
                                </div>

                                <div class="ant-pro-table-list-toolbar-setting-item">
                                    <a-popover placement="bottomRight" arrowPointAtCenter trigger="click"
                                        overlayClassName="ant-pro-table-column-setting-overlay">
                                        <template #title>
                                            <div class="ant-pro-table-column-setting-title">
                                                <a-checkbox v-model:checked="columnState.checkAll"
                                                    :indeterminate="columnState.indeterminate"
                                                    @change="handleColumnAllClick">
                                                    列展示 / 排序
                                                </a-checkbox>
                                                <a @click="reset">重置</a>
                                            </div>
                                        </template>
                                        <template #content>
                                            <span class="ant-pro-table-column-setting-list">
                                                <drag-container lockAxis="y" dragClass="ant-pro-table-drag-ghost"
                                                    dropClass="ant-pro-table-drop-ghost"
                                                    @drop="({ removedIndex, addedIndex }) => move(removedIndex, addedIndex)">
                                                    <template :key="column.key" v-for="column in dynamicColumnItems">
                                                        <draggable>
                                                            <div class="ant-pro-table-column-setting-list-item">
                                                                <drag-icon />
                                                                <a-checkbox :checked="column.checked"
                                                                    @change="handleColumnChange($event, column)">
                                                                    {{ column.label }}
                                                                </a-checkbox>
                                                            </div>
                                                        </draggable>
                                                    </template>
                                                </drag-container>
                                            </span>
                                        </template>
                                        <a-tooltip title="列设置">
                                            <setting-outlined />
                                        </a-tooltip>
                                    </a-popover>
                                </div>
                            </div>
                        </a-col>
                    </a-row>
                </a-form>
            </div>
            <a-card :body-style="{ padding: 0 }" ref="elRef">
                <a-table row-key="id" :size="state.tableSize" :loading="state.loading" :columns="dynamicColumns"
                    :data-source="state.dataSource" :pagination="{
                        showSizeChanger: true,
                        current: state.current,
                        pageSize: state.pageSize,
                        total: state.total,
                        showTotal: total => `共 ${total} 条`,
                    }" @change="handleTableChange">
                    <!-- <template #expandedRowRender="{ record }">
                        <div class="table-role-permission-card">
                            <a-row :gutter="12">
                                <a-col style="height: 48px" :span="12" :key="permission.id" v-for="permission in record.permissions">
                                    <a-row :gutter="16">
                                        <a-col :span="4">{{ permission.label }}</a-col>
                                        <a-col>
                                            <a-tag color="cyan" :key="action" v-for="action in permission.actions">
                                                {{ action }}
                                            </a-tag>
                                        </a-col>
                                    </a-row>
                                </a-col>
                            </a-row>
                        </div>
                    </template> -->
                    <template #bodyCell="{ record, column }">
                        <template v-if="column.dataIndex === 'action'">
                            <a-space>
                                <a @click="dialogChatHistoryRef.init(record)"
                                    v-permission="[`system:menu:update`]">查看原消息</a>
                            </a-space>
                        </template>
                    </template>
                </a-table>
            </a-card>
        </div>

        <dialogChatHistory ref="dialogChatHistoryRef" />
    </page-container>
</template>

<script lang="ts" setup>
    import { reactive, ref, onMounted } from 'vue';
    import { ReloadOutlined, ColumnHeightOutlined, SettingOutlined } from '@ant-design/icons-vue';
    import { Container as DragContainer, Draggable } from '@/components/draggable';
    import { dictDataListByDictType } from '@/api/user/dict';
    import type { Pagination, TableColumn } from '@/typing';
    import { useFetchData } from '@/utils/hooks/useFetchData';
    import { useTableDynamicColumns } from '@/utils/hooks/useTableColumn';
    import DragIcon from '@/components/table/drag-icon.vue';
    import { getSensitiveWordsRecordPage } from '@/api/smss/keyword';
    import dialogChatHistory from './components/dialog-chat-history.vue';

    const baseColumns: TableColumn[] = [
        {
            title: '关键词',
            dataIndex: 'word',
            width: 120,
        },
        {
            title: '词性',
            dataIndex: 'wordClass',
            width: 80,
        },
        {
            title: '触发时间',
            dataIndex: 'msgtimeFormat',
            width: 120,
        },
        {
            title: '消息发送方',
            dataIndex: 'msgfromName',
            width: 150,
        },
        {
            title: '消息接收方',
            dataIndex: 'receiveName',
            width: 150,
        },
        {
            title: '消息内容',
            dataIndex: 'text',
        },
        {
            title: '操作',
            dataIndex: 'action',
            width: 100,
        },
    ];

    const {
        state: columnState,
        dynamicColumns,
        dynamicColumnItems,
        handleColumnAllClick,
        handleColumnChange,
        reset,
        move,
    } = useTableDynamicColumns(baseColumns, { needRowIndex: false });
    const queryParams = reactive<any>({});
    const fetchDataContext = reactive({
        current: 1,
        pageSize: 10,
        tableSize: 'middle', // 'default' | 'middle' | 'small'
        stripe: true,
        executeImmediately: false,
        isList: false,
        requestParams: {
            ...queryParams,
        },
    });

    // 表格数据和加载
    const { context: state, reload } = useFetchData(getSensitiveWordsRecordPage, fetchDataContext);

    const dialogChatHistoryRef = ref();
    const dictTypes = ref<any>([]);

    onMounted(async () => {
        // 重置
        const responseData: any = await dictDataListByDictType({
            dictType: 'word_class',
        });
        dictTypes.value = responseData.data;
        fetchDataContext.executeImmediately = true;
        reset();
    });

    const handleTableChange = ({ current, pageSize }: Pagination) => {
        fetchDataContext.current = current;
        fetchDataContext.pageSize = pageSize;
    };

    const handleEdit = (record: Record<string, any>) => {
        dialogModalRef.value.init(record);
    };

    const handleSearch = () => {
        const { time } = queryParams;
        if (time?.length === 2) {
            queryParams.startTime = `${time[0]} 00:00:00`;
            queryParams.endTime = `${time[1]} 23:59:59`;
        }else{
            delete queryParams.startTime;
            delete queryParams.endTime;
        }
        fetchDataContext.current = 1;
        fetchDataContext.requestParams = { ...queryParams };
    };
    const handleReset = () => {
        Object.keys(queryParams).forEach(key => {
            delete queryParams[key];
        });
        handleSearch();
    };
</script>
